
/*
*Pool Public Licence version 0.1 or later
*Released on 20th April 2008.
*Any voilations can be repoted at paritosh@wikiocean.net
*What is treated as voilations can be found at www.wikiocean.net/ppl1-voilations* 
******************************************************************************
* The contents of this file are subject Affero GPL v3 and later with additional conditions.
* The additional conditions are to be considered as part of the Affero GPL v3 and later.
* The additional conditions will supersede the Affero GPLv3 and later in case of conflict.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the License at http://www.gnu.org/licenses/agpl.html
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya.
* created by Paritosh Pungaliya are Copyright (C) Paritosh Pungaliya; All Rights Reserved.
* Contributions are Copyright (C) 2001-2008 Paritosh Pungaliya.

* Objective of the additional terms (license) 
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencie(s).
* 3) To avoid a situation where big corporates or investors can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the openness changes in companies that get Venture Capital funding.)
* (if you agree to this logic I invite you to our group to work together)

* Additional conditions
*  0) Source code will also include
* 	a) data dictionaries, data ontologies which are used to alter the behavior of code or to control           the features of application.
* 	b) Any code generated or derived automatically or manually from this code or logic
*  1) The revenue generated by deploying, implementing , selling services and other activities
*  	 based on this source code should be shared 100%, between the people working on it.
*  2) Capital invested should be given only fixed rate of return or linked to revenue/surplus growth for limited time.
*  3) People working on the project should always have an option to replace the capital provider in full or part with lower cost capital.
*  4) Their should not be any ownership which can be sold as a claim on future profit to be generated from the work of people working on the code.
*  5) Brand thus generated should belong to the group.
*  6) For old and new members revenue sharing should be equal for same work equivalent.
*  7) The share of revenue should be decided by bidding for work before allocation of work within the group.
*  8) Before bidding various method of measuring the work should be clearly defined and published in public domain. Any change in process should also be publised in public domain imediately.
*  9) All data related to to revenue sharing should be published as and when generated in public domain.
*  10) For group of people having size more than 10 people will have to make it open online for others to participate in bids. 
*  11) All people involved in related and sub project will be treated as a group.
*  12) Once this license is being used for a certain code then all and any other software services being provided by the group should complusorilly come under 100% revenue sharing.
*  13) Cross subsidization should not happen under this revenue share, no additional benefit should be drawn from the people, by the employing agency.
*  14) Any position or knowledge or legal structure created relating to people working on code, which adversely affects the spirit of 100% revenue share will be treated as a violation.
*  15) Revenue sharing defined.
*     a) includes direct revenue and also intangible gains like brand, and organization.
*     b) No personal judgment should be involved in judging the distribution of revenue.It has to be pre-defined formula based.
*     c)100% of revenue should be shared before expenses and recievers should have control over what expenses to incur.
*     d)For the work done in any month by contributing group member, working on any project can be given revenue share from the work done by the group, for a maximum of 18 months after that month.
*     e)Revenue should be apportioned to the month in which work is done and not when received.
*  The group fulfilling the above conditions also has to be a wiki ecosystem further defined in www.wekosystem.org or read about Wekosystem at www.wikiocean.net

*  ******************************************************************************
*/  
package pool.preprocess;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import pool.tablename.Pool;
import pool.tablename.Trans_property_details;
import property.Property;
import file.SearchRecord;
import utility.ConvertToLower;
import utility.Input;
import database.RecordSearch;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;

public class Getrate implements Process
{
	String type;
	Pool pool;
	String TablaName;
	DBManager database;
	//SearchRecord sr;
	RecordSearch sr;
	String TYPE="type";
	String Group = "Usergroup";
	String RETURN="return";
	String ITEM="item";
	String GETRATE="getrate"; 
	String OLDVALUE="oldvalue";
	GetIdName gid;
	String UOM="uom";
	String BUYER = "buyer";
	String TABLENAME="tablename";
	String CONVERSION="conversion";
	String ITEMCODE="itemcode";
	String typeofrate ="";
	String INPUT="input";
	String OUTPUT="output";
	String order_date =""; 
	Hashtable<Object, Object> TransactionDetailmap =new Hashtable<Object, Object>();
	Hashtable<Object, Object> Transactionmap = new Hashtable<Object, Object>();
	Property property;
	String input;
	String output;
	
	public Hashtable<Object, Object> gethashtable() 
	{
		return TransactionDetailmap;
	}

	public void process(String value) 
	{	
		Hashtable<Object, Object>table = new Hashtable<Object, Object>();
		
		Transactionmap = pool.getmasterHashtabel();
		TransactionDetailmap = pool.getHashtabel();
		
		table.put("mid", value);
		table.put("pid",TABLENAME);
		table.put("td", "null");
		sr.setConditionMap(table);
		String line[] = sr.getArrayFromResultSet();
		String tablename="";
		for(int i=0;i<line.length;i++)
		{
			String splitline[] =line[i].split("\t");
			tablename = splitline[Column.pv_index-1];
			if(tablename.equals("0"))
				tablename =  splitline[Column.vt_index-1];
			else
				tablename =gid.getItem(tablename);
		}
		
		if(tablename.toLowerCase().equals(TablaName))
		{
			table.put("pid", TYPE);
			table.put("pv", GETRATE);
			table.put("td", "null");
			sr.setConditionMap(table);
			line = sr.getArrayFromResultSet();
			for(int i=0;i<line.length;i++)
			{
				try 
				{
					String splitline[] =line[i].split("\t");
					typeofrate = (splitline[Column.ref_index-1]);
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
				}
			}
			table.clear();
			table.put("mid",value);
			table.put("pid", RETURN);
			table.put("td", "null");
			sr.setConditionMap(table);
			line = sr.getArrayFromResultSet();
			String returnvalue="";
			for(int i=0;i<line.length;i++)
			{
				String splitline[] = line[i].split("\t");
				returnvalue = splitline[Column.pv_index-1];
				if(returnvalue.equals("0") || returnvalue.equals("no$"))
					returnvalue = splitline[Column.vt_index-1];
				else
					returnvalue = gid.getItem(returnvalue);
			}
			if(Transactionmap.containsKey("delivery_date")==false)
			{
				String pattern = "yyyy-MM-dd HH:MM:ss";
				SimpleDateFormat sdm = new SimpleDateFormat(pattern);
				String delivery_date = sdm.format(new Date());				
				Transactionmap.put("delivery_date", delivery_date);
				Transactionmap.put("order_date", delivery_date);
			}
			table.clear();
			table.put("mid",value);
			table.put("pid", OLDVALUE);
			table.put("td", "null");
			sr.setConditionMap(table);
			line = sr.getArrayFromResultSet();
			table.clear();
			for(int i=0;i<line.length;i++)
			{	
				String splitline[] = line[i].split("\t");
				String pv = splitline[Column.pv_index-1];
				table.put("mid", pv);
				table.put("td", "null");
				sr.setConditionMap(table);
				String result[] = sr.getArrayFromResultSet();
				table.clear();
				for(int l=0;l<result.length;l++)
				{
				String split[] = result[l].split("\t");
				String propertyvalue = split[Column.pv_index-1];
				if(propertyvalue.equals("0"))
					propertyvalue = split[Column.vt_index-1];
				else
					propertyvalue = gid.getItem(propertyvalue);
				table.put(gid.getItem(split[Column.pid_index-1]), propertyvalue);
				}
			}
			table = ConvertToLower.convertHashKey(table);
			if(table.containsKey("property"))
			{
				try 
				{
					String property=table.get("property").toString();
					if(Transactionmap.containsKey(property))
						property=Transactionmap.get(property).toString();
					else
					{
						property = gid.getId(property);
						Vector<Object> propertyvector =pool.gettplVector();
						for(int j=0;j<propertyvector.size();j++)
						{
							Trans_property_details tpd =(Trans_property_details) propertyvector.get(j);
							if(tpd.PropertyMap.containsKey("pid"))
								if(tpd.PropertyMap.get("pid").equals(property))
								{
									property = tpd.PropertyMap.get("pv").toString();
									if(property.equals("0"))
										property =tpd.PropertyMap.get("vt").toString();
									else
										property = gid.getItem(property);
								}
						}
					}
					table.remove("property");
					table.remove("type");
					
					Hashtable<Object, Object>Condition= new Hashtable<Object, Object>();
					Condition.put("id", property);
					ResultSet rs= database.getSelect("transaction",table.elements(),Condition);
					if(rs.next())
					{
						order_date = rs.getString(table.get("return").toString());
					}
				} catch (Exception e) 
				{
					e.printStackTrace();
				}
				
			}
			if(Transactionmap.containsKey(BUYER))
			{
				String buyer =gid.getId(Transactionmap.get(BUYER).toString());
				Hashtable<Object, Object> hash = new Hashtable<Object, Object>();
				hash.put("mid", buyer);
				hash.put("pid", Group);
				hash.put("ref", typeofrate);
				hash.put("td", "null");
				sr.setConditionMap(hash);
				line = sr.getArrayFromResultSet();
				for(int i=0;i<line.length;i++)
				{
					String splitline[] = line[i].split("\t");
					Group = splitline[Column.pv_index-1];
				}
				if(line.length==0)
				Group =gid.getId("DG1");
			}
			else
				Group =gid.getId("DG1");
			try 
			{	
			
				String itemname = gid.getId(TransactionDetailmap.get(ITEM).toString());
				ResultSet rs=null;
				if(order_date.length()==0)
				{
				   order_date = Transactionmap.get("order_date").toString();
				   rs = database.getSelect("select * from rate_master where item='"+itemname+"' and usergroup='"+Group+"' and  buysell='"+typeofrate+"' and FD<='"+order_date+"' and td is null"); 
				}
				else
				  rs = database.getSelect("select * from rate_master where item='"+itemname+"' and usergroup='"+Group+"' and  buysell='"+typeofrate+"' and FD<='"+order_date+"' and td>='"+order_date+"'");
				
				String rate="0";
				if(rs.next())
					rate =rs.getString("rate");
				TransactionDetailmap.put(returnvalue.toLowerCase(), rate);
				property.setMid(value);
				property.setPid(CONVERSION);
				String objectvalue = (property.getValue());
				if(!objectvalue.equals("no$"))
				{	
					objectvalue = gid.getId(objectvalue);
					property.setMid(objectvalue);
					property.setPid(INPUT);
					input= property.getValue();
					property.setMid(objectvalue);
					property.setPid(OUTPUT);
					output= property.getValue();
					checkUom();
					pool.setHashtable(TransactionDetailmap);
				}	
				else
					pool.setHashtable(TransactionDetailmap);
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				TransactionDetailmap.put(returnvalue.toLowerCase(), "0");
				pool.setHashtable(TransactionDetailmap);
			}	
		}	
	}

	public void setObject(Object object, DBManager database) 
	{
	 this.pool = (Pool) object;
	 this.database = database;	  
	 gid = new GetIdName(database);
	 TYPE = gid.getId(TYPE);
	 GETRATE = gid.getId(GETRATE);
	 Group = gid.getId(Group);
	 RETURN = gid.getId(RETURN);
	 TABLENAME = gid.getId(TABLENAME);	 
	 CONVERSION = gid.getId(CONVERSION);
	 ITEMCODE = gid.getId(ITEMCODE);
	 INPUT = gid.getId(INPUT);
	 UOM = gid.getId(UOM);
	 OUTPUT = gid.getId(OUTPUT);
	 OLDVALUE = gid.getId(OLDVALUE);
	 property=new Property(database);
	 sr =new RecordSearch(database);
	 }

	public void setType(String type,String TablaName) 
	{
		this.type =type;
		this.TablaName = TablaName.toLowerCase();
	}
	
	private void checkUom()
	{	
		String uom="";		
			try 
			{
			
				String item = gid.getId(TransactionDetailmap.get("item").toString());
				if(TransactionDetailmap.containsKey("uom"))				
					 uom = gid.getId(TransactionDetailmap.get(UOM).toString());
				else
				{	
					String MATSREPATH = Input.MASTERREPORTSPATH + item + item + "_pv" + Input.FILRFORMAT;
					Hashtable<Object, Object> table =new Hashtable<Object, Object>();
					table.put("pv", item);
					table.put("pid", ITEMCODE);
					table.put("td", "null");
					sr.setConditionMap(table);
					String result[] = sr.getArrayFromResultSet();
					for(int i=0;i<result.length;i++)
					{
						String splitresult[] =result[i].split("\t");
						property.setMid(splitresult[Column.mid_index-1]);
						property.setPid(UOM);
						uom = gid.getId(property.getValue());
						if(uom.equals("0"))
							uom =property.getValue();
					}	
				}	
				
				order_date = Transactionmap.get("order_date").toString();
				ResultSet rs = database.getSelect("select * from rate_master where item='"+item+"' and usergroup='"+Group+"' and  buysell='"+typeofrate+"' and FD<='"+order_date+"' and td is null");
				if(rs.next())
				{
					String itemuom = gid.getId(rs.getString("Unit"));					
					if(!uom.equalsIgnoreCase(itemuom) && uom.length()>0)
					{
						property.setMid(uom);
						property.setPid(CONVERSION);
						String conversionobject =gid.getId(property.getValue());
						property.setMid(conversionobject);
						property.setPid(itemuom);
						String value = property.getValue();		
						TransactionDetailmap.put(output, Double.toString(Double.parseDouble(value)*Double.parseDouble(TransactionDetailmap.get(input).toString())));
					}
				}	
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
			
		}		
	

}
